import axios from 'axios'
import { getStore } from '../utils/tools'
import Vue from 'vue'
import store from '../vuex/store'
import { app } from '../main'
import { baseUrl } from '../config/baseUrls'

axios.defaults.timeout = 60000;
axios.defaults.baseURL = baseUrl;
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
axios.defaults.withCredentials = true
const oldUrl = axios.defaults.baseURL;

//请求拦截
axios.interceptors.request.use(function (config) {
    // let token = getStore('tk')
    let token = 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMTI4R0NNIn0.M00vfJ1DOHXkAXeqj2nIe1z31K8q_s9c2bIr6sA4W13YDLlfCyXQgTFBcJsNACf2kWOp5tO7XZyYsljsBwgX041iJdncs_NnFAuqCgUlbOkD4Eh_A60pyT08Zhn3NYHBo9E63aR_woftTl3WVwFySE6qXlo4fs6Bcg5g8e0Xgms.pSfuvtlBvp13k7dx.gv898p2_cwivsGbyBXFq9WuCbXUleoY5k_l-XWVWlqH5b4vqbt8v81gtkVJYjlTAJVe7Ig5U5uNJy3xOGBMTFbNd0H0CeyOjopWMSzXvbPBKunEYtMdkeYHm1-KuWM0h3Q_Cq4zuW9e6JSBXpAs4mEm-GBcW6du6vwzn2P2F1fPkQso8QY-GhbaJUWFgd8OsNXJS-APkAHBfr9ISkITu2UMXx8-6fmokEIymNwOy5jMY9e9qk3_6eQIRvu73f5rmwJJo0PkVtoPG9Qrtgg3W6nHvgQAA1GFA2sgKqiEh1bz36j9rKGL-xXv1nRk6qsSdUsSaS9KA99k9Pc_nygi0ts6tHmNYikCyLKre7TKitVfM_Q3KzNu0wM2Tkst9EPmfUyo3hvxIEUJ0v773cnJcFiQaKcHuvNSaZPzXsyGE2symjYtWcHUxX1FQARVKX9mBx58P9jxhGu-r4Am1t3DeHRisyP_PIxg82-gNrZe8greY6gWltK5fyBRLW5SKJTPY6PYr8yi0pZgXi2EbB829fMsPpfNAbRxMIySsyvFcYR_jVsWRSrA06w2SZmplBAF7eOD4qqeOVGdSaGK1mhczJ0_BaZpUudTOoVvPqU7UiE3dZNk70OS2NgdtTtGUlJsA1Qw2Wud5xvDS2T18MFflfMRavfj4M6_0vuBk3n9GR3VjqXk_JKOD296ORad09e56IrWSuB_4jwNe7M2_hE5WWxvrdhtb3hvUQtpoVMqAeUF39BKHeSSt5SpspigzznhHrfVsrKVft7ARVF1GRd7AtopTqe_GY-3aTN_46-Rt-HAT_NLF4Wq4RznTwZh_aTNA3U2sUM_GQbmrVmceLbwIIEQtzuaZPDgWn5n8nHnfkdYvYuk7HINKgySfj6zLpAYqAeKa2uTHUK42C6RCiWKcwTsbVPPBRciXaT889JTbbyXly7-JM049LqJAWlFcWtb_zzcvvOOUsOoPLL_SRly3FIFOWR2ebri69P0jdr4HHAsYdPad4LRg-ub_G6cxF8uucnyN64TZSktoL_M8EdG5Jg4EMEQ-Y81hav91nhSXIuyILz8zSNOuZ4irCQLwkTPIB32yfB8GpEz8h44dZSpSbXWwPrBAmMu6irrudJqA-w0zH3gMQd8dHW9rSCE0dlHaJETiRKjhpa7inhtkF8PjIc8wDbhn3FCtaVCSHu4OxdwZWgfEhOoorH7zcRAD9cXy0_3FwhGdhFVjkq2ItimqCnx-ACS4RLDa61DyNYM0ZN0907K5SN8Ctqo1XHNMtuJsLhzCd-WqZQRs2CNeCDsNJLsz8LbscVaiVoAG_aRveVu37GSdtX3Zf1SeU8ZJYiNu_YqAKLQ79NSa32dVQ6ShLGxfgGPKhknGl7d7v7MrooYBZnpeKFXmyztJOxZHfXtvsR2scW053MYYxbNMlOrKDiiKV3czOAnD-6Pgl6Fn6m3HeK_CuFhShjBGsJOWLdTmw5O4qnzpU7oC00o1.r5Co08hR1TbLmMxYYuiLaQ';
    // let topDeptId = getStore('topDeptId')
    let topDeptId = 'ff808081389aa60301389ac3109e0068';
    // let topDeptName = getStore('topDeptName')
    let topDeptName = '软件事业部';
    // let postName = getStore('postName')
    let postName = null ;
    config.data = JSON.stringify(config.data)
    if (token && ( config.url.indexOf('app-file') > 0 || config.url.indexOf('app-sys') > 0 ) ) {
        config.headers.Authorization = token;
    }else if(token){
        token += ('|topDeptId=' + encodeURI(topDeptId) + '|topDeptName=' + encodeURI(topDeptName) + '|postName=' + encodeURI(postName))
        config.headers.Authorization = token;
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

//响应拦截
axios.interceptors.response.use(function (response) {
    if (response.data.errCode == 2) {
        window.location.href = 'www.ctnma.cn'
    }
    return response
}, function (error) {
    return Promise.reject(error.response.data)
})

//封装axios的get请求
export function fetch(url, params, Origin) {
    if (Origin) {
        axios.defaults.baseURL = Origin;
    }
    console.log('url',url)
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(response => {
                axios.defaults.baseURL = oldUrl;
                resolve(response.data)
            })
            .catch((error) => {
                axios.defaults.baseURL = oldUrl;
                reject(error)
            })
    })
}

//封装axios的post请求
export function post(url, data = {}, Origin, openLoading) {
    if (Origin) {
        axios.defaults.baseURL = Origin;
    }
    return new Promise((resolve, reject) => {

        //每一次http请求的唯一标识码
        const timestamp = new Date().getTime();

        loadingBar('start', timestamp, openLoading);
        axios.post(url, data)
            .then(response => {
                axios.defaults.baseURL = oldUrl;
                resolve(response.data);
                loadingBar('finish', timestamp, openLoading);
            })
            .catch((error) => {
                axios.defaults.baseURL = oldUrl;
                reject(error);
                loadingBar('error', timestamp, openLoading);
            })
    })
}

//封装axios的下载数据流转换成excel
export function DownLoadToExcel(url, data = {}, fileName, Origin, openLoading) {
    if (Origin) {
        axios.defaults.baseURL = Origin;
    }
    fileName = fileName + '.xls'
    return new Promise((resolve, reject) => {

        //每一次http请求的唯一标识码
        const timestamp = new Date().getTime();

        loadingBar('start', timestamp, openLoading);
        axios.post(url, data, {
            responseType: "blob",
        }).then(response => {
            axios.defaults.baseURL = oldUrl;
            const blob = new Blob([response.data], { type: "application/vnd.ms-excel" });
            if ("download" in document.createElement("a")) {
                // 非IE下载
                const elink = document.createElement("a");
                elink.download = fileName;
                elink.style.display = "none";
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
            } else {
                // IE10+下载
                navigator.msSaveBlob(blob, fileName);
            }
            loadingBar('finish', timestamp, openLoading);
        }).catch((error) => {
            axios.defaults.baseURL = oldUrl;
            loadingBar('error', timestamp, openLoading);
        })
    })
}

//开启loading
function loading(isLoading, openLoading) {
    if (openLoading) {
        Vue.nextTick(function () {
            store.commit('FETCH_LOADING', isLoading)
        })
    }
}

//开启loading 进度条
function loadingBar(action, timestamp, openLoading) {
    if (app && openLoading) {
        if (action == 'start') {
            store.commit('pushPromiseIntoCase', timestamp);
            app.$LoadingBar.start();
            loading(true, openLoading)
        }
        if (action == 'finish') {
            store.commit('finishPromiseInCase', timestamp);
            store.dispatch('checkoutIsFininsh').then(res => {
                if (res) {
                    loading(false, openLoading)
                    app.$LoadingBar.finish();
                }
            });
        }
        if (action == 'error') {
            store.commit('finishPromiseInCase', timestamp);
            store.dispatch('checkoutIsFininsh').then(res => {
                if (res) {
                    loading(false, openLoading)
                    app.$LoadingBar.error();
                }
            });
        }
    }
}
